package com.heer.gymnasium.module.common.views;

/**
 * Created by Administrator on 2017/8/3.
 */


import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.module.advise.beans.Ad;
import com.heer.gymnasium.module.advise.beans.AdMainBean;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.R;
import com.heer.gymnasium.db.AdvertisementDao;
import com.heer.gymnasium.module.main.views.MainActivity;
import com.heer.gymnasium.util.AdvertiseUtil;
import com.heer.gymnasium.util.LoadImageUtil;
import com.heer.gymnasium.util.Session;

import retrofit2.Call;
import retrofit2.Response;

public class SplashActivity extends BaseActivity {

    private final int MSG_LOGIN_SUCCESS = 100;
    private final int MSG_LOGIN_FAIL = 101;
    private final int MSG_VERSION_CHECK_TIMEOUT = 102;
    private final int UPDATE_TEAY_TIME = 103;

    private int delayTime = 4;// 广告4秒倒计时
    private List<Ad> alist;
    private ImageView welComeImg, adImg;
    private RelativeLayout rl;
    private TextView dTime;
    private TextView skipBtn;
    // 是否首次登陆
    private Boolean myIsfirst = null;
    Editor edited = null;
    SharedPreferences share = null;
    private Context context;
    private boolean adIsFinish = false;
    private Ad mAdver = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_splash);
        welComeImg = (ImageView) findViewById(R.id.iv_welcome_img);
        rl = (RelativeLayout) findViewById(R.id.rl_show_ad);
        skipBtn = (TextView) findViewById(R.id.ll_ad_skip_btn);

        adImg = (ImageView) findViewById(R.id.iv_ad_img);
        dTime = (TextView) findViewById(R.id.tv_time);
        alist = AdvertisementDao.getAdDataList();// 查询广告信息
        if (alist != null && alist.size() > 0) {
            mAdver = alist.get(alist.size() - 1);
            File f = new File(mAdver.getAndroidimg());// 获取最新的一条广告信息
            if (f.exists() && !isDeadline(alist.get(alist.size() - 1))) {//// 判断文件存在，并且没有过期
                Bitmap b = AdvertiseUtil.scaleImgSize(f);
                adImg.setImageBitmap(b);
                adIsFinish = true;
                b = null;
            }
        }

        skipBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToMain();
                finish();
            }
        });
        adImg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(mAdver.getUrl())) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(mAdver.getUrl());
                    intent.setData(content_url);
                    startActivity(intent);
                }
//                if ("0".equals(mAdver.getFlag())) {// 0 代表这个广告可以点击
//					/*
//					 * Intent i = new Intent(context, AdverActivity.class);
//					 * i.putExtra("url_key", mAdver.getUrl());
//					 * context.startActivity(i); finish();
//					 */
//                }
            }
        });

        // 启动一个线程，去删除过期的广告信息
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (Ad ad : alist) {
                    if (isDeadline(ad)) {
                        // 如果当前广告过期，则删除数据库中的记录，和本地的文件
                        AdvertiseUtil.deleteCachedAdverImg(context, ad);
                        AdvertisementDao.deleteAd(ad);
                    }
                }
            }
        }).start();
    }

    /**
     * 判断某个广告是否过期 过期 true 未过期 false
     *
     * @param adver
     * @return
     */
    private boolean isDeadline(Ad adver) {
        long deadLine = Long.parseLong(adver.getEnd());
        // 获取当前时间的时间戳
        long currentLine = AdvertiseUtil.getCurrentDateMil();
        if (currentLine > deadLine) {// 过期
            return true;
        }
        return false;
    }

    protected void onResume() {
        super.onResume();
        // 获取广告
//           mAppHelper.apiService().getMainAd("25").enqueue(new BaseCallback<ApiResponse<List<AdMainBean>>>() {
//            @Override
//            public void onSuccess(Call<ApiResponse<List<AdMainBean>>> call, Response<ApiResponse<List<AdMainBean>>> response) {
//                if (response.body().isSccessful() && response.body().getData().size() > 0) {
//                    initAd(response.body().getData());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ApiResponse<List<AdMainBean>>> call, Throwable t) {
//                super.onFailure(call, t);
//            }
//        });

        /**
         * 超时设置
         */
        handler.sendEmptyMessageDelayed(MSG_VERSION_CHECK_TIMEOUT, 1 * 1000);
    }


    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }

    private void initAd(List<AdMainBean> data) {
        List<Ad> list = new ArrayList<Ad>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null; //初始化date

        for (AdMainBean item:data) {
            Ad ad = new Ad();
            ad.setAndroidimg(LoadImageUtil.getLoadImageUrl(item.getImages()));
            ad.setUrl(item.getLink_url());
            try {
                date = sdf.parse(item.getEnd_date()); //Mon Jan 14 00:00:00 CST 2013
                ad.setEnd(String.valueOf(date.getTime()));
            } catch (ParseException e) {
                e.printStackTrace();
                ad.setEnd("0");
            }

            list.add(ad);
        }
        AdvertiseUtil.getLoadingAd(context,list);
    }

    @Override
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler.removeMessages(MSG_VERSION_CHECK_TIMEOUT);
            handler = null;
        }
        super.onDestroy();
    }

    private void jumpToMain() {
        Intent intent;
        if (Session.getUserIsLogin()) {
            Log.e("sessid", Session.getUserId());
            intent = new Intent(mContext, MainActivity.class);
        } else {
            intent = new Intent(mContext, LoginActivity.class);
        }
        startActivity(intent);
        finish();
    }

    private Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOGIN_SUCCESS:
                    jumpToMain();
                    break;
                case MSG_LOGIN_FAIL:

                    break;
                case MSG_VERSION_CHECK_TIMEOUT:
                    // 启动页面版本检查接口调用：3秒中没有返回，跳转页面
                    skipToLoginOrMain();
                    break;
                case UPDATE_TEAY_TIME:
                    if (adIsFinish) {
                        if (delayTime > 0) {
                            welComeImg.setVisibility(View.GONE);
                            rl.setVisibility(View.VISIBLE);
                            dTime.setText(delayTime + "");
                            handler.sendEmptyMessageDelayed(UPDATE_TEAY_TIME, 1000);
                            delayTime--;
                        } else {
                            jumpToMain();
                            finish();
                        }
                    } else {
                        jumpToMain();
                        finish();
                    }
                    break;
            }
        };
    };

    private void skipToLoginOrMain() {
        handler.sendEmptyMessageDelayed(UPDATE_TEAY_TIME, 1000);
    }
}
